package com.igl.talk.android.client.core.service;

import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;

/*
 * @author Adam Wieczorek
 *
 * 21/04/2014
 *
 * All rights reserved.
 */

public class ServiceManager {


    /**
     * The Service Manager is responsible for managing the life-cycle of the Service
     * and the Activities that bind to it.
     *
     * @author Kaleb
     *
     */
    private static final String LOG_TAG = ServiceManager.class.getSimpleName() + ".class";

    // Keep track of the service run state.
    private boolean serviceStarted = false;

    // The context from the application.
    private Context context;
    // The intent we will use to start the service and bind activities.
    private Intent helloServiceIntent = null;
    // Only for debugging purposes
    private String serviceName;

    public ServiceManager(Context context, Class service)
    {
        this.context = context;
        helloServiceIntent = new Intent(this.context, service);
        serviceName = service.getCanonicalName();
    }

    /**
     * Bind a Service Connection from a component (probably an Activity) to the
     * service so it can receive status updates.
     *
     * @param serviceConnection
     */
    public void bindService(ServiceConnection serviceConnection)
    {
        Log.d(LOG_TAG, "Binding service " + serviceName);
        this.context.bindService(helloServiceIntent, serviceConnection,
                Context.BIND_AUTO_CREATE);
    }

    /**
     * Determine if the service is started.
     * @return The run state of the service.
     */
    public boolean isServiceStarted()
    {
        return serviceStarted;
    }

    /**
     * Start the service.
     */
    public void startService()
    {
        serviceStarted = true;
        this.context.startService(helloServiceIntent);
        Log.d(LOG_TAG, "Service " + serviceName + " started.");
    }

    /**
     * Stop the service.
     */
    public void stopService()
    {
        serviceStarted = false;
        this.context.stopService(helloServiceIntent);
        Log.d(LOG_TAG, "Service " + serviceName + " stopped.");
    }

    /**
     * Unbind a Service Connection from a component (probably an Activity).
     * @param serviceConnection
     */
    public void unbindService(ServiceConnection serviceConnection)
    {
        this.context.unbindService(serviceConnection);
        Log.d(LOG_TAG, "Service " + serviceName + " unbinded.");
    }
}
